<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="org.apache.commons.fileupload.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'control.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
 		<%!
 			String newName(String name){
 				int pos=name.lastIndexOf(".");
 				String prefix=name.substring(pos==-1?0:pos);
 				return UUID.randomUUID()+prefix;//随机生成一个32位的文件名
 			}
 		 %>
    	<%
    		DiskFileItemFactory d=new DiskFileItemFactory();
    		ServletFileUpload up=new ServletFileUpload(d);
    		up.setHeaderEncoding("utf-8");
    		List<FileItem> fields=up.parseRequest(request);//拿到所有的域
    		String picPath=application.getRealPath("image");//存放路径
    		for(FileItem f:fields){
    			if(f.isFormField()){//文本域
    				out.print("<h1>这是表单域,"+f.getFieldName()+",value"+f.getString("utf-8")+"</h1>");
    			}else{//文件域
    				if(f.getName()==null||f.getName().equals(""))
    				continue;
    				
    				out.print("<h1>文件域，文件名是："+f.getName()+"</h1>");
    				String newFileName=newName(f.getName());
    				f.write(new java.io.File(picPath,newFileName));//存入文件
    				out.print("<img src='image/"+newFileName+"'/>");
    			}	
    		}		
    	 %>
  </body>
</html>
